<?php
/**
 * 采购订单明细(模型)
 * (model)
 */
namespace App\Models\Purchase;

use App\Models\Basics\SettlementMethod;
use App\Models\Basics\Supplier;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use Illuminate\Database\Eloquent\Model;
class PurchaseOrderDetail extends Model
{
    protected $table = 'purchase_order_detail';

    protected $guarded = [];

    //收货状态
    const RECEIVED_NO = 1; //未收货
    const RECEIVED_PART = 2; //部分到货
    const RECEIVED_ALL = 3; //完全到货
    public static $_receivedStatus = [
        self::RECEIVED_NO => '未收货',
        self::RECEIVED_PART => '部分到货',
        self::RECEIVED_ALL => '完全到货'
    ];

    /**
     * 采购单
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function purchase(){
        return $this->belongsTo(PurchaseOrder::class,'purchase_no','purchase_no');
    }

    /**
     * 采购备货明细
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function stocking_detail(){
        return $this->hasMany(PurchaseStockingDetail::class,'order_detail_id');
    }

    /**
     * 公司sku
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    public function purSupplier(){
        return $this->hasOneThrough(
            Supplier::class,
            PurchaseOrder::class,
            'purchase_no',//中间表
            'id',//目标表
            'purchase_no',//当前模型
            'supplier_id'//中间表
        );
    }

    public function purSettlementMethod(){
        return $this->hasOneThrough(
            SettlementMethod::class,
            PurchaseOrder::class,
            'purchase_no',//中间表
            'id',//目标表
            'purchase_no',//当前模型
            'settlement_method_id'//中间表
        );
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function($detail) {
            $detail->stocking_detail()->delete();
        });
    }

    /**
     * 更新采购订单明细
     * Abandoned
     * @param $data [id=>num,...]
     * @param $action "increment" "decrement"
     * @param $field
     * @return mixed
     */
    public static function updatePurchaseDetail($data,$action,$field){
        return self::query()->find(array_keys($data))->each(function ($query) use ($data,$action,$field) {
            $query->{$action}($field , $data[$query->id]);
        });
    }
}
